package com.fxd.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxd.core.util.PageUtils;
import com.fxd.core.util.Query;
import com.fxd.model.product.CategoryEntity;
import com.fxd.shopping.product.dao.CategoryDao;
import com.fxd.shopping.product.dto.Catalog2DTO;
import com.fxd.shopping.product.service.CategoryBrandRelationService;
import com.fxd.shopping.product.service.CategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1，查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2，组装成父子的树形结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Munus = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            //查找二级子菜单
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Munus;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到三级子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO 1，检查
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity parent = this.getById(catelogId);
        if (parent.getParentCid() != 0) {
            findParentPath(parent.getParentCid(), paths);
        }
        return paths;
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return lambdaQuery()
                .eq(CategoryEntity::getParentCid, 0).list();
    }

    @Override
    public Map<String, List<Catalog2DTO>> getCatalogJson() {
        // 查出所有1级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        if (CollectionUtils.isEmpty(level1Categorys)) return new HashMap<>();
        return level1Categorys.stream().collect(Collectors.toMap(item1 -> item1.getCatId().toString(), item1 -> {
            // 二级分类
            List<CategoryEntity> level2Entitys = lambdaQuery()
                    .eq(CategoryEntity::getParentCid, item1.getCatId()).list();
            List<Catalog2DTO> catalog2DTOS = null;
            if (CollectionUtils.isNotEmpty(level2Entitys)) {
                catalog2DTOS = level2Entitys.stream().map(item2 -> {
                    List<CategoryEntity> level3Entitys = lambdaQuery().eq(CategoryEntity::getParentCid, item2.getCatId())
                            .list();

                    List<Catalog2DTO.level3Catalog> catalog3DTOs = null;
                    if (CollectionUtils.isNotEmpty(level3Entitys)) {
                        catalog3DTOs = level3Entitys.stream().map(item3 -> {
                            Catalog2DTO.level3Catalog level3Catalog = new Catalog2DTO.level3Catalog(item2.getCatId().toString()
                                    , item3.getCatId().toString()
                                    , item3.getName());
                            return level3Catalog;
                        }).collect(Collectors.toList());

                    }

                    Catalog2DTO catalog2DTO = new Catalog2DTO(item1.getCatId().toString()
                            , item2.getCatId().toString(), item2.getName()
                            , catalog3DTOs);
                    return catalog2DTO;
                }).collect(Collectors.toList());
            }
            return catalog2DTOS;
        }));
    }
}